﻿#ifndef __SS_MYSQL_CONNECTION_H__
#define __SS_MYSQL_CONNECTION_H__
#include "../ssMySQLDefin.h"
#include "container/ssLineBuffer.h"
#include "byteStream/ssReadBytes.h"
#include <string>

namespace StarSeeker
{

class ssMySQLConnection
{
	friend class ssMySQLStmt;
	friend class ssMySQLPool;
public:
	ssMySQLConnection();
	virtual ~ssMySQLConnection();
	//初始化连接
	bool Init(const char *pIP, u32	port, const char *pAccount, const char *pPW, const char *pDBName);
	//结束连接
	void Exit();
	//设置字符集
	void SetCharacter(const char *pc);
	//设置数据库
	void SelectDB(const char *pDBName);
	//执行语句不返回数据
	bool Execute(const char *sql);
	//查询语句并返回数据
	//bool Query(const char *sql);
	//获取查询结果
	bool StoreResult();
	//开始事务
	bool Transaction();
	//提交事务
	bool Commit();
	//回滚事务
	bool Rollback();
	//获取一行结果
	ssReadBytes GetOneResult();
	void GetOneResult(ssReadBytes& rb);
	//清理缓存
	void CleanBuffer();
	//清空结果缓冲区
	void ClearResult();
	//获取结果行数
	u64 GetRows() { return m_resultSet.Count(); }
protected:
	//重新预处理
	virtual void RePrepare();
	//连接数据库
	bool Connect();
	//尝试重连
	bool TyrReconnect();
	//错误检测
	void CheckError(const char * str);
	//是否重连
	bool ReconnectTest();

	MYSQL*			m_pConnect;
	MYSQL_RES*		m_res;
	std::string		m_IP;
	u32				m_port;
	std::string		m_account;
	std::string		m_password;
	std::string		m_name;
	std::string		m_character;
	std::string		m_serverVersion;
	std::string		m_clientVersion;
public:
	u64					m_rows;			//行数
	u32					m_fields;		//字段数
	i64					m_affectedRows;	//操作的行数
	u64					m_insertID;		//新插入的ID
	ssLineBuffer		m_resultSet;	//结果集
	u32					m_errno;		//错误码
	std::string			m_error;		//错误描述
	bool				m_free;
};

}
#endif
